<template>
  <div class="app-container">
    <div
      v-show="
        !modifyInfo.visible && !detailsInfo.visible && !assetDetailsInfo.visible
      "
      v-if="proxy.$permission('inspectionRecord:list')"
    >
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <new-page-filter
          v-model:query="filterInfo.query"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
        >
          <template v-slot:filter-installDate>
            <el-date-picker
              @change="timeChange($event, 'installDate')"
              v-model="installDate"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="datetimerange"
              range-separator="至"
              align="right"
              :shortcuts="$fn.pickerOptionsFn()"
              :default-time="[
                new Date(2000, 1, 1, 0, 0, 0),
                new Date(2000, 1, 1, 23, 59, 59),
              ]"
              start-placeholder="安装开始日期"
              end-placeholder="安装结束日期"
            ></el-date-picker>
          </template>
          <template v-slot:filter-inspectorDate>
            <el-date-picker
              @change="timeChange($event, 'inspectorDate')"
              v-model="inspectorDate"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="datetimerange"
              range-separator="至"
              align="right"
              :shortcuts="$fn.pickerOptionsFn()"
              :default-time="[
                new Date(2000, 1, 1, 0, 0, 0),
                new Date(2000, 1, 1, 23, 59, 59),
              ]"
              start-placeholder="检查开始日期"
              end-placeholder="检查结束日期"
            ></el-date-picker>
          </template>
        </new-page-filter>
      </div>
      <div class="filter-wrapper">
        <new-page-filter :filter-btn="filterInfo.btnList">
          <template v-slot:filter-remove>
            <el-button :disabled="!canRemove" @click="remove">删除</el-button>
          </template>
          <template v-slot:filter-uploadProduct>
            <el-upload
              :headers="uploadInfo.headers"
              :show-file-list="false"
              :on-error="uploadError"
              :on-success="importProduct"
              :before-upload="beforeProductUpload"
              :action="uploadInfo.action"
            >
              <el-button>导入模板</el-button>
            </el-upload>
          </template>
        </new-page-filter>
      </div>

      <table-container
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :query="filterInfo.query"
        :checkBox="true"
        :tabIndex="true"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :row-class-name="tableRowClassOtherName"
        @pageInfo="pageInfo"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-orderNo="scope">
          <span class="slip-edit" @click="showDetail(scope.row)">{{
            scope.row.orderNo || '-'
          }}</span>
        </template>
        <template v-slot:col-assetName="scope">
          <span
            v-if="scope.row.assetName"
            class="slip-edit"
            @click="showAssetDetail(scope.row)"
            >{{ scope.row.assetName }}</span
          >
          <span v-else>-</span>
        </template>
      </table-container>
    </div>

    <!-- 详情-->
    <InspectionRecordDetails
      v-if="detailsInfo.visible"
      v-model:visible="detailsInfo.visible"
      :title="detailsInfo.title"
      :id="detailsInfo.id"
      @returnBack="getList"
    />
    <asset-card-details
      v-if="assetDetailsInfo.visible"
      v-model:visible="assetDetailsInfo.visible"
      :id="assetDetailsInfo.id"
      @returnBack="getList"
    />
    <!-- 新增或修改 -->
    <modify
      v-if="modifyInfo.visible"
      v-model:visible="modifyInfo.visible"
      v-model:title="modifyInfo.title"
      @returnModify="returnModify"
      :id="modifyInfo.id"
    />
    <page-dialog
      v-show="dialogInfo.visible"
      :title="dialogInfo.title"
      v-model:visible="dialogInfo.visible"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
    >
      <div class="asset-msg">
        <div class="asset-msg-label">
          <i class="el-icon-warning"></i>{{ dialogInfo.msg }}：
        </div>
        <el-radio-group v-model="dialogInfo.flag">
          <el-radio :label="true">当前页数据</el-radio>
          <el-radio :label="false">全部页数据</el-radio>
        </el-radio-group>
      </div>
    </page-dialog>
  </div>
</template>

<script setup name="inspectionRecord">
import {
  getInspectionRecordPage,
  deleteInspectionRecord,
  excelListInspectionRecord,
} from '@/api/quality'
import axios from 'axios'
import { ElLoading } from 'element-plus'
import { fatchTemplateByCode } from '@/api/base'
import { getSupplierAll, getDeptAll } from '@/api/core'
import { exportTemplateExcel } from '@/api/pub.js'
import Modify from './modify'
import InspectionRecordDetails from './details'
import AssetCardDetails from '@/views/asset/assetManage/assetCard/details'

const { proxy } = getCurrentInstance()
const installDate = ref([])
const inspectorDate = ref([])
// 过滤相关配置
const filterInfo = ref({
  query: {
    sort: 'create_time desc',
  },
  searchList: [
    {
      label: '记录单号',
      value: 'orderNoLike',
      componentType: 'input',
      event: search,
    },
    {
      label: '合同编号',
      value: 'contractNoLike',
      componentType: 'input',
      event: search,
    },
    {
      label: '使用部门',
      value: 'deptIdMult',
      query: {
        // deptAuth: 'id',
        status: 1,
      },
      api: getDeptAll,
      componentType: 'slip-select',
      multiple: true,
      event: search,
    },

    {
      label: '安装日期',
      value: 'installDate',
      slot: true,
      event: search,
    },

    {
      label: '产品名称',
      value: 'productNameLike',
      componentType: 'input',
      event: search,
    },
    {
      label: '规格',
      value: 'standardLike',
      componentType: 'input',
      event: search,
    },
    {
      label: '生产厂家',
      value: 'brandNameLike',
      componentType: 'input',
      event: search,
    },

    {
      label: '批号',
      value: 'batchNumberLike',
      componentType: 'input',
      event: search,
    },
    {
      label: '供应商',
      value: 'supplierIdMult',
      componentType: 'slip-select',
      api: getSupplierAll,
      query: {
        // supplierAuth: 'supplierId',
        sort: 'create_time desc',
      },
      clearable: true,
      multiple: true,
      keyField: 'supplierName',
      valueField: 'supplierId',
      event: search,
    },
    {
      label: '检查人',
      value: 'inspector',
      asValue: 'inspector',
      componentType: 'select-user',
      highlightRow: true,
      checkBox: false,
      event: search,
    },
    {
      label: '检查日期',
      value: 'inspectorDate',
      slot: true,
      event: search,
    },
  ],
  searchBtn: [{ type: 'button', label: '搜索', event: search }],
  btnList: [
    {
      type: 'button',
      label: '新增',
      event: create,
      show: proxy.$permission('inspectionRecord:add'),
    },
    {
      type: 'slot',
      label: '删除',
      value: 'remove',
      show: proxy.$permission('inspectionRecord:remove'),
    },
    {
      type: 'button',
      label: '下载模板',
      event: downloadTemplate,
      show: proxy.$permission('inspectionRecord:download'),
    },
    {
      type: 'slot',
      value: 'uploadProduct',
      show: proxy.$permission('inspectionRecord:import'),
    },
    {
      type: 'button',
      label: '导出excel',
      event: exportExcel,
      show: proxy.$permission('inspectionRecord:excel'),
    },
    // {
    //   type: 'button',
    //   label: '打印',
    //   event: print,
    //   show: proxy.$permission('inspectionRecord:print'),
    // },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  api: undefined,
  selections: [],
  data: [],
  fieldList: [
    {
      label: '记录单号',
      value: 'orderNo',
      type: 'slot',
    },
    {
      label: '合同编号',
      value: 'contractNo',
    },
    {
      label: '使用部门',
      value: 'deptName',
    },
    {
      label: '安装日期',
      value: 'installDate',
    },
    {
      label: '安装地点',
      value: 'installLocation',
    },
    {
      label: '产品名称',
      value: 'productName',
    },
    {
      label: '规格',
      value: 'standard',
    },
    {
      label: '生产厂家',
      value: 'brandName',
    },
    {
      label: '生产日期',
      value: 'productionDate',
    },
    {
      label: '批号',
      value: 'batchNumber',
    },
    {
      label: '供应商',
      value: 'supplierName',
    },
    {
      label: '供应商电话',
      value: 'supplierPhone',
    },
    {
      label: '售后电话',
      value: 'supportPhone',
    },
    {
      label: '包装情况',
      value: 'packagingTypeValue',
    },
    {
      label: '器械情况',
      value: 'conditionTypeValue',
    },
    {
      label: '注册证号',
      value: 'regCerNo',
    },
    {
      label: '检查结果',
      value: 'inspectionResultValue',
    },
    {
      label: '检查人',
      value: 'inspectorName',
    },
    {
      label: '检查日期',
      value: 'inspectorDate',
    },
    {
      label: '资产',
      value: 'assetName',
      type: 'slot',
    },
    { label: '创建人', value: 'createUserName' },
    { label: '创建时间', value: 'createTime' },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '90',
    btList: [
      {
        label: '修改',
        event: update,
        show: proxy.$permission('inspectionRecord:update'),
      },
      {
        label: '删除',
        event: remove,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: proxy.$permission('inspectionRecord:remove'),
      },
    ],
  },
})
//新增或更新相关
const modifyInfo = ref({
  visible: false,
  title: '',
  id: '',
})
const detailsInfo = ref({
  visible: false,
  id: '',
})
const assetDetailsInfo = ref({
  visible: false,
  id: '',
})
const uploadInfo = ref({
  action: axios.defaults.baseURL + '/quality/inspectionRecord/import/excel',
  headers: {
    Authorization: proxy.$store.state.user.token,
  },
  loading: {},
})
const dialogInfo = ref({
  visible: false,
  title: '提示',
  btLoading: false,
  type: '',
  msg: '',
  width: '400px',
  flag: true,
  btList: [
    { label: '关闭', event: handleClose, show: true },
    {
      label: '导出',
      type: 'primary',
      event: checkConfirm,
      show: true,
    },
  ],
})
const page = ref({
  page: true,
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
})

const canRemove = computed(() => {
  return tableInfo.value.selections.length
})
getList()
function timeChange(val, str) {
  if (str === 'installDate') {
    if (val && val.length) {
      filterInfo.value.query.installDateGreater = val[0]
      filterInfo.value.query.installDateLess = val[1]
    } else {
      filterInfo.value.query.installDateGreater = ''
      filterInfo.value.query.installDateLess = ''
    }
  } else if (str === 'inspectorDate') {
    if (val && val.length) {
      filterInfo.value.query.inspectorDateGreater = val[0]
      filterInfo.value.query.inspectorDateLess = val[1]
    } else {
      filterInfo.value.query.inspectorDateGreater = ''
      filterInfo.value.query.inspectorDateLess = ''
    }
  }
}
function pageInfo(obj) {
  page.value = obj
}
function exportExcelList() {
  let params = {
    ...filterInfo.value.query,
    ...page.value,
    page: dialogInfo.value.flag,
  }
  excelListInspectionRecord(params).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
async function print() {
  dialogInfo.value.visible = true
  dialogInfo.value.type = 'print'
  dialogInfo.value.msg = '请选择当数据打印范围'
  dialogInfo.value.btList[1].label = '打印'
  dialogInfo.value.flag = true
}
function printList() {
  fatchTemplateByCode({
    resourceCode: 'assCard:printListCard',
    isDefault: 1,
  }).then((res) => {
    if (res && res.success) {
      let temp = proxy.$fn.getPrintTemp(res.data[0])
      getPrintData(temp, dialogInfo.value.flag)
    }
  })
}
function checkConfirm() {
  if (dialogInfo.value.type === 'excel') {
    exportExcelList()
  } else if (dialogInfo.value.type === 'print') {
    printList()
  }
  dialogInfo.value.visible = false
  dialogInfo.value.msg = ''
}
function handleClose() {
  dialogInfo.value.visible = false
}
// 获取列表
function getList() {
  tableInfo.value.api = getInspectionRecordPage
  tableInfo.value.refresh = Math.random()
}
// 搜索
function search() {
  // 重置分页
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
// 创建
function create() {
  modifyInfo.value.id = ''
  modifyInfo.value.visible = true
  modifyInfo.value.title = '新增用前检查记录'
}
// 编辑
function update(row) {
  sessionStorage.setItem('storeRowId', row.id)
  modifyInfo.value.id = row.id
  modifyInfo.value.visible = true
  modifyInfo.value.title = '修改用前检查记录'
}

function showDetail(row) {
  sessionStorage.setItem('storeRowId', row.id)
  detailsInfo.value.id = row.id
  detailsInfo.value.visible = true
}
function showAssetDetail(row) {
  sessionStorage.setItem('storeRowId', row.id)
  assetDetailsInfo.value.id = row.assetId
  assetDetailsInfo.value.visible = true
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}

function tableRowClassOtherName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }
  return ''
}

//删除
function remove(row = undefined) {
  if (row && row.id) {
    deleteInspectionRecord([row.id]).then((resp) => {
      if (resp && resp.success) {
        getList()
      }
    })
  } else {
    let ids = getIds()
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        deleteInspectionRecord(ids).then((res) => {
          if (res && res.success) {
            getList()
          }
        })
      })
  }
}
function getIds(row = undefined) {
  let ids = []
  if (row && row.id) {
    ids.push(row.id)
  } else {
    ids = tableInfo.value.selections.map((row) => row.id)
  }
  return ids
}

function exportExcel() {
  dialogInfo.value.visible = true
  dialogInfo.value.type = 'excel'
  dialogInfo.value.msg = '请选择数据导出范围'
  dialogInfo.value.btList[1].label = '导出'
  dialogInfo.value.flag = true
}
function returnModify() {
  if (modifyInfo.value.id) {
    getList()
  } else {
    search()
  }
}
function downloadTemplate() {
  exportTemplateExcel('inspection_record_import').then((res) => {
    if (res) {
      proxy.$fn.parseExcel(res)
    }
  })
}

function uploadError(err) {
  if (err) {
    proxy.$message.error({
      message: '系统错误',
      duration: 3000,
      showClose: true,
    })
  }
  uploadInfo.value.loading.close()
}
function beforeProductUpload(file) {
  //发生请求时打开加载动画
  uploadInfo.value.loading = ElLoading.service({
    fullscreen: true,
    background: 'rgba(255,255,255,.4)',
  })
  let fileType = ['xlsx']
  let fileSize = proxy.$store.state.permission.systemConfig.max_file_size
  let isFileType = fileType.some(
    (type) => file.name.split('.')[file.name.split('.').length - 1] === type
  )
  const isLt = file.size / 1024 / 1024 < fileSize
  if (!isFileType) {
    proxy.$message.error({
      message: `文件格式不正确, 请上传 ${fileType.join(' / ')} 格式文件!`,
      showClose: true,
      duration: 3500,
    })
    uploadInfo.value.loading.close()
    return false
  }
  if (!isLt) {
    proxy.$message.error({
      message: `上传文件大小不能超过 ${fileSize} MB!`,
      showClose: true,
      duration: 3500,
    })
    uploadInfo.value.loading.close()
    return false
  }
  return isFileType && isLt
}
function importProduct(resp) {
  uploadInfo.value.loading.close()
  if (resp && resp.success) {
    proxy.$message.success({
      duration: 3000,
      showClose: true,
      message: resp.msg,
    })
    getList()
  } else {
    proxy.$message.error({
      message: resp.msg,
      duration: 0,
      showClose: true,
    })
  }
}
</script>

<style scoped></style>
